import $ from './jquery';
import { saveAs } from 'file-saver';

/**
 * @desc 如果使用jq导出那么必须在挂载组件的生命周期ComponentDidMount/useEffect 运行初始化函数 wordExport导出函数挂载在$原型上
 * @author 自己看 annotate
 */
export const initExportForJquery = () => {
  (function () {
    // 绑定wordExport导出函数到$原型
    $.fn.wordExport = function (exPortData) {
      _initData(exPortData);
      let options = {
        maxWidth: 624,
      };
      // 在操作所选元素之前克隆它
      let markup = $(this).clone();
      console.log(markup);
      //从输出中删除隐藏的元素
      markup.each(function () {
        let self = $(this);
        if (self.is(':hidden')) self.remove();
      });

      // 使用标签行内数据嵌入所有图像
      let images = Array();
      let img = markup.find('img');

      for (let i = 0; i < img.length; i++) {
        // 计算输出图像的尺寸
        let w = Math.min(img[i].width, options.maxWidth);
        let h = img[i].height * (w / img[i].width);
        // 创建用于将图像转换为数据 URL 的画布
        let canvas = document.createElement('CANVAS');
        canvas.width = w;
        canvas.height = h;
        // 绘图
        let context = canvas.getContext('2d');
        context.drawImage(img[i], 0, 0, w, h);
        // 获得canvas base64格式图片
        let uri = canvas.toDataURL('image/png');
        $(img[i]).attr('src', img[i].src);
        img[i].width = w;
        img[i].height = h;
        // 将编码的图像保存到array
        images[i] = {
          type: uri.substring(uri.indexOf(':') + 1, uri.indexOf(';')),
          encoding: uri.substring(uri.indexOf(';') + 1, uri.indexOf(',')),
          location: $(img[i]).attr('src'),
          data: uri.substring(uri.indexOf(',') + 1),
        };
      }

      //准备带有图像数据的 mhtml 放入文件底部
      let mhtmlBottom = '\n';
      for (let i = 0; i < images.length; i++) {
        mhtmlBottom += '--NEXT.ITEM-BOUNDARY\n';
        mhtmlBottom += 'Content-Location: ' + images[i].location + '\n';
        mhtmlBottom += 'Content-Type: ' + images[i].type + '\n';
        mhtmlBottom += 'Content-Transfer-Encoding: ' + images[i].encoding + '\n\n';
        mhtmlBottom += images[i].data + '\n\n';
      }
      mhtmlBottom += '--NEXT.ITEM-BOUNDARY--';
      const fileContent = getModelHtml(markup.html(), mhtmlBottom, exPortData);
      // 解决page-break-before: always;解析成为break-before: page;问题 ！！！！！！！！！！！！！！！！！！！！！
      const resForPageBreakBeforeFileContent = fileContent.replaceAll('break-before: page;', 'page-break-before:always;');
      console.log(resForPageBreakBeforeFileContent);
      const blob = new Blob([resForPageBreakBeforeFileContent], {
        type: 'application/msword;charset=utf-8',
      });
      saveAs(blob, exPortData.fileName + exPortData.fileType);
    };

    function _initData(exPortData) {
      exPortData.fileName = typeof exPortData.fileName !== 'undefined' ? exPortData.fileName : 'jQuery-Word-Export';
      exPortData.fileType = typeof exPortData.fileType !== 'undefined' ? exPortData.fileType : '.doc';
    }

    function getModelHtml(mhtml, mhtmlBottom, exPortData) {
      let styles,
        updateStyles,
        header,
        footer = '';
      if (exPortData.styles) {
        styles = exPortData.styles;
      }
      if (exPortData.updateExportCss) {
        updateStyles = exPortData.updateExportCss;
      }
      if (exPortData.isHeader) {
        header = '<div style="mso-element:header;padding-bottom:20px;" id="h1">\n' + '<p class="MsoHeader">' + exPortData.header + '</p>\n' + '</div>';
      }
      if (exPortData.isFooter) {
        footer =
          '<div style="mso-element:footer;text-align: center;" id="f1">\n' +
          '<p class="MsoHeader">' +
          exPortData.footer +
          '</p>\n' +
          '<p class="MsoNum"><span class="num" style="mso-field-code: PAGE "></span>/<span style="mso-field-code:NUMPAGES"></span>\n</p>\n' +
          '</div>';
      }

      /*
        html标签中，和meta标签下面的判断，用来默认显示页面视图模式 否则打开word是Web版式!!!!!!!!!!!!!!!!!!!!!!!!!!!!
       */
      return `
                <!DOCTYPE html>
                <html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns:m=\"http://schemas.microsoft.com/office/2004/12/omml\" xmlns=\"http://www.w3.org/TR/REC-html40\">
                <head>
                    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
					<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val=\"Cambria Math\"/><m:brkBin m:val=\"before\"/><m:brkBinSub m:val=\"--\"/><m:smallFrac m:val=\"off\"/><m:dispDef/><m:lMargin m:val=\"0\"/> <m:rMargin m:val=\"0\"/><m:defJc m:val=\"centerGroup\"/><m:wrapIndent m:val=\"1440\"/><m:intLim m:val=\"subSup\"/><m:naryLim m:val=\"undOvr\"/></m:mathPr></w:WordDocument></xml><![endif]-->
                    <style type="text/css">
                        table#hrdftrtbl {
                            width: 1px;
                            height: 1px;
                            overflow: hidden;
                        }

                        p.MsoHeader {
                            font-size: 20px;
                            font-weight: bold;
                            text-align: center;
                        }

                        p.MsoFooter, li.MsoFooter, div.MsoFooter {
                            margin: 0in;
                            mso-pagination: widow-orphan;
                            tab-stops: center 3.0in right 6.0in;
                            font-size: 20pt;
                            font-weight: bold
                        }

                        table {
                           border: 0;
                           border-collapse:collapse;
                           border-spacing:0;
                           border-right: 1px solid #000000;
                           border-bottom: 1px solid #000000;
                           text-align: center;
                        }
                        table th {
                            border-left: 1px solid #000000;
                            border-top: 1px solid #000000;
                        }

                        table td {

                            border-left: 1px solid #000000;
                            border-top: 1px solid #000000;
                        }
	                      p.MsoNum{
	                      		 text-align: center;
						            }

                        <!-- /*FontDefinitions*/
                        @page WordSection {
							mso-title-page:yes; //首页不显示页眉页脚
							mso-page-numbers:0; //起始页码从0开始
                            mso-header-margin: 20px;
                            mso-footer-margin: 20px;
                            mso-header: h1;
                            mso-footer: f1;
                            /*可以自定义   设置生成Word的页边距！！！！！！！！！！！！！！！！！！！！！！！！！！！！！*/
                            /*size:595.3pt 841.9pt;*/
                            /*margin:30.0pt 30.0pt 30.0pt 30.0pt;*/
                            /*mso-header-margin:42.55pt;*/
                            /*mso-footer-margin:49.6pt;*/
                            /*mso-paper-source:0;*/
                        }

                        div.WordSection {
                            page: WordSection;
                        }

                        -->
                        ${styles}
                        ${updateStyles}
                    </style>
                </head>
                <body lang=ZH-CN style="tab-interval:21.0pt">
                <div class="WordSection">
                    ${mhtml}

                    <table id="hrdftrtbl" border="0" cellspacing="0" cellpadding="0">
                        <tbody>
                        <tr>
							<td>
								${header}
							</td>
							<td>
								${footer}
							</td>
                        </tr>
                        </tbody>
                    </table>
                </div>
                </body>
                </html>
             ${mhtmlBottom}
    `;
    }
  })();
};
